//
//  SSBaseTableView.swift
//  SSCommentUI
//
//  Created by 松松 on 2019/5/20.
//

import UIKit
import MJRefresh

protocol BaseTableViewDelegate : NSObjectProtocol {
    func getDate (tableView:BaseTableView,pageNum:Int,pageSize:Int)
}

class BaseTableView: UITableView {
    typealias BaseTableViewGetDataBlcok = (_ pageNum:Int,_ pageSize:Int)->Void
    var pageNum : Int = FIRST_PAGE_NUM
    var pageSize : Int = 10
    weak var baseTableViewDelegate : BaseTableViewDelegate?
    var getDataBlock : BaseTableViewGetDataBlcok?


    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    init(frame:CGRect, style: UITableViewStyle,refreshBlock:@escaping BaseTableViewGetDataBlcok) {
        super.init(frame: frame, style: style)
        setup()
        self.getDataBlock = refreshBlock
    }

    fileprivate func setup(){
        self.tableFooterView = UIView()
        estimatedRowHeight = 0
        estimatedSectionFooterHeight = 0
        estimatedSectionHeaderHeight = 0
        self.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.pageNum = FIRST_PAGE_NUM
            self?.mj_footer?.isHidden = false
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5, execute: {
                self?.mj_header?.endRefreshing()
            })
            self?.getDataBlock?(self!.pageSize,self!.pageNum)
            self?.getData()

        })
        self.mj_footer = MJRefreshBackFooter(refreshingBlock: { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5, execute: {
                self?.mj_footer?.endRefreshing()
            })
            self?.getDataBlock?(self!.pageSize,self!.pageNum)
            self?.getData()
        })
    }


    func pushSuccess(count:Int){
        self.mj_header?.endRefreshing()
        self.mj_footer?.endRefreshing()
        if count < pageSize{
            self.mj_footer?.isHidden = true
        }
        self.pageNum += 1
        self.reloadData()
    }

    fileprivate func getData(){
        self.baseTableViewDelegate?.getDate(tableView: self, pageNum: self.pageNum, pageSize: self.pageSize)
    }

}

